﻿using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Utilities
{
    public class Cryptography
    {
        #region Fields

        private static Byte[] key = { };
        private static Byte[] IV = { 38, 55, 206, 48, 28, 64, 20, 16 };
        private static String stringKey = "!ImGalIb?#";

        #endregion

        #region Public Methods

        private static String _secretKey;
        public static String SecretKey
        {
            get { return String.IsNullOrEmpty(_secretKey)? stringKey:_secretKey; }
            set { _secretKey = value; }
        }
        public static String Encrypt(string text)
        {
            try
            {
                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] byteArray = Encoding.UTF8.GetBytes(text);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cryptoStream.Write(byteArray, 0, byteArray.Length);
                cryptoStream.FlushFinalBlock();
                return Convert.ToBase64String(memoryStream.ToArray());
            }

            catch (Exception ex)
            {
                // Handle Exception Here
            }
            return String.Empty;
        }

        public static String Decrypt(String text)
        {
            try
            {
                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] byteArray = Convert.FromBase64String(text);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
                cryptoStream.Write(byteArray, 0, byteArray.Length);
                cryptoStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                // Handle Exception Here
            }
            return String.Empty;
        }

        #endregion
    }
}
